package it.jx.wormholes.physics;
import java.util.Iterator;
import java.util.Vector;

/**
 * A zero-dimensional mass
 * 
 * @author Lorenzo Porzi
 * 
 */
public class Mass {
	public Point3D position; // Position
	public Point3D speed; // Speed
	public Point3D force; // The force applied to this mass
	public double mass; // Mass

	private Vector<LocalForce> localForces; // Local forces

	public Mass(Point3D position, Point3D speed, double mass) {
		this.position = position;
		this.speed = speed;
		this.mass = mass;

		localForces = new Vector<LocalForce>();
		force = new Point3D(0, 0, 0);
	}

	public Mass(double x, double y, double z, double mass) {
		this(new Point3D(x, y, z), new Point3D(0.0, 0.0, 0.0), mass);
	}

	public void addLocalForce(LocalForce f) {
		localForces.add(f);
	}

	public void removeLocalForce(LocalForce f) {
		localForces.remove(f);
	}

	public void updateForce(Point3D externalForce, double dt) {
		force = new Point3D(0.0, 0.0, 0.0);
		LocalForce f;

		// Update local forces
		for (Iterator<LocalForce> i = localForces.iterator(); i.hasNext();) {
			f = i.next();

			if (!f.update(dt)) {
				i.remove();
				continue;
			}

			force = force.sum(f.value());
		}

		// Add external forces
		force = force.sum(externalForce);
	}

	private void integrateSpeed(double dt) {
		speed.x += dt * force.x / mass;
		speed.y += dt * force.y / mass;
		speed.z += dt * force.z / mass;
	}

	private void integratePosition(double dt) {
		position.x += dt * speed.x;
		position.y += dt * speed.y;
		position.z += dt * speed.z;
	}

	public void integrate(double dt) {
		integrateSpeed(dt);
		integratePosition(dt);
	}

	public String toString() {
		return "pos: " + position + " - speed: " + speed + " - mass: " + mass;
	}
}
